//
//  XMCSTableViewController.m
//  XMcityselector
//
//  Created by zhifenx on 2019/7/10.
//  Copyright © 2019 zhifenx. All rights reserved.
//

#import "CityViewController.h"

#import "XMCSDataOpreation.h"
#import "XMCSBaseInfoModel.h"
#import "XMAreaModel.h"
#import "XMCSPopularCitiesModel.h"
#import "XMCSConfiguration.h"
//#import "XMCSSearchTableViewController.h"
#import "XMCSTopToolsTableViewCell.h"
#import "XMCSTableViewHeaderView.h"
//#import "XMCSFileManager.h"
#import "XMCSContentTableViewCell.h"


#define XMWeakSelf(type)  __weak typeof(type) weak##type = type;
#define XMStrongSelf(type)  __strong typeof(type) type = weak##type;

#define kHeaderCitiesSectionIndex @"切换区县"

@interface CityViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataMutableArray;
@property (nonatomic, strong) NSMutableArray *firstLetterMutableArrary;
@property (nonatomic, strong) NSMutableArray *sectionFirstLetterMutableArrary;
@property (nonatomic, strong) NSMutableArray <NSString *> *popularCitiesNameMutableArray;
@property (nonatomic, strong) NSMutableArray <NSString *>*historyRecordNameMutableArray;
@property (nonatomic, strong) NSMutableArray <NSString *>*headerCitiesNameMutableArray;

@property (nonatomic, strong) NSMutableArray <XMCSBaseInfoModel *>*historyRecordMutableArray;
@property (nonatomic, strong) NSMutableArray <XMCSBaseInfoModel *>*headerCitiesMutableArray;
@property (nonatomic, strong) NSMutableArray <XMCSBaseInfoModel *>*otherCitiesMutableArray;

@property (nonatomic, strong) UIButton *searchButton;
//@property (nonatomic, strong) XMCSSearchTableViewController *resultVC;
@property (nonatomic, strong) XMCSTopToolsTableViewCell *popularCitiesCell;
@property (nonatomic, strong) XMCSTopToolsTableViewCell *historyRecordCell;
@property (nonatomic, strong) XMCSTopToolsTableViewCell *headerCitiesCell;
@property (nonatomic, strong) XMCSContentTableViewCell *otherCell;

@property (nonatomic, strong) XMCSTableViewHeaderView *headerView;

@property (nonatomic, strong) XMCSDataOpreation *dataOpreation;
@property (nonatomic, strong) XMCSConfiguration *config;
@property (nonatomic, weak) id<CityViewControllerDelegate> delegate;
@property (nonatomic, strong) XMCSBaseInfoModel *currentCityModel;

@end

@implementation CityViewController

- (instancetype)initWithConfiguration:(XMCSConfiguration *)config delegate:(id<CityViewControllerDelegate>)delegate {
    self = [super init];
    if (self) {
        _config = config;
        _delegate = delegate;
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _config = [[XMCSConfiguration alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[XMCSFileManager getImageWithName:_config.leftBarButtonItemImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction)];
//    
//    if (_config.searchButton) {
//        self.searchButton = _config.searchButton;
//    }
//    self.navigationItem.titleView = self.searchButton;
    
    [self.view addSubview:self.tableView];
    [self initData];
}

#pragma mark -- UITableViewDelegate/UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMutableArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = self.dataMutableArray[section];
    return arr.count/arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    XMCSContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMCSContentTableViewCell"];
    XMCSContentTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行，而不是从cell重用队列中取出
    if (indexPath.section < self.dataMutableArray.count) {
        if (indexPath.row < [self.dataMutableArray[indexPath.section] count]) {
            NSString * indexStr =  self.sectionFirstLetterMutableArrary[indexPath.section];
        if (_config.popularCitiesMutableArray.count > 0 && [self.sectionFirstLetterMutableArrary[indexPath.section] isEqualToString:_config.popularCitiesTitle]) {//热门城市
                if (!_popularCitiesCell) {
                    _popularCitiesCell = [[XMCSTopToolsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"XMCSTopToolsTableViewCell"];
                    [_popularCitiesCell setupData:self.popularCitiesNameMutableArray];
                    [_popularCitiesCell setSelectionStyle:UITableViewCellSelectionStyleNone];
                    XMWeakSelf(self);
                    [self.popularCitiesCell topToolsCellSelectCityBlock:^(NSInteger index) {
                        XMStrongSelf(self);
                        [self didSelectPopularCities:self.config.popularCitiesMutableArray[index]];
                    }];
                }
                return _popularCitiesCell;
            }else if (self.historyRecordNameMutableArray.count > 0 && [self.sectionFirstLetterMutableArrary[indexPath.section] isEqualToString:_config.historicalRecordTitle]) {//最近访问
                if (!_historyRecordCell) {
                    _historyRecordCell = [[XMCSTopToolsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"XMCSTopToolsTableViewCell"];
                    [_historyRecordCell setSelectionStyle:UITableViewCellSelectionStyleNone];
                    XMWeakSelf(self);
                    [self.historyRecordCell topToolsCellSelectCityBlock:^(NSInteger index) {
                        XMStrongSelf(self);
                        [self selectCityCallBack:self.historyRecordMutableArray[index]];
                    }];
                }
                [_historyRecordCell setupData:self.historyRecordNameMutableArray];
                return _historyRecordCell;
            } else if (![indexStr containsString:_config.historicalRecordTitle] && ![indexStr containsString:_config.popularCitiesTitle]){//最近访问
                NSLog(@"%ld--------%ld",indexPath.section,indexPath.row);
                
                if (!cell) {
                    cell = [[XMCSContentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"XMCSContentTableViewCell"];
                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                 }
                 NSArray * sectionArray = self.dataMutableArray[indexPath.section];
                 [cell setupOtherData:sectionArray];
                return cell;
            }
         }
    }
    return cell;
}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//
//{
//
//    UIView *headView = [[UIView alloc]init];
//
//    headView.backgroundColor = [UIColor clearColor];
//
////    if (section!=0)
//
////    {
//         //标题背景
//
//        UIView *biaotiView = [[UIView alloc]init];
//
////        biaotiView.backgroundColor = [UIColor whiteColor];
//
//        biaotiView.frame=CGRectMake(0, 0, 320, 30);
//
//        [headView addSubview:biaotiView];
//
//         //标题文字
//
//        UILabel *lblBiaoti = [[UILabel alloc]init];
//
//        lblBiaoti.backgroundColor = [UIColor clearColor];
//
//        lblBiaoti.textAlignment = NSTextAlignmentLeft;
//
//        lblBiaoti.font = [UIFont systemFontOfSize:15];
//
//        lblBiaoti.textColor = [UIColor blackColor];
//
//        lblBiaoti.frame = CGRectMake(15, 7.5, 200, 15);
//
////        lblBiaoti.text = [headerList objectAtIndex:section-1];
//
//        [biaotiView addSubview:lblBiaoti];
//
////    }
//
//    return headView;
//
//}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.sectionFirstLetterMutableArrary[section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.firstLetterMutableArrary;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section < self.dataMutableArray.count) {
        if (indexPath.row < [self.dataMutableArray[indexPath.section] count] && ![self.sectionFirstLetterMutableArrary[indexPath.section] isEqualToString:_config.popularCitiesTitle]) {
            XMCSBaseInfoModel *model = self.dataMutableArray[indexPath.section][indexPath.row];
            [self selectCityCallBack:model];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 44;
    if (indexPath.section < self.dataMutableArray.count) {
        NSString * indexStr =  self.sectionFirstLetterMutableArrary[indexPath.section];
        if (indexPath.row < [self.dataMutableArray[indexPath.section] count]) {
            if ( _config.popularCitiesMutableArray.count > 0 && [self.sectionFirstLetterMutableArrary[indexPath.section] isEqualToString:_config.popularCitiesTitle]) {//热门城市
               height = _config.popularCitiesCellHeight;
            }
            
           if (!_config.hideHistoricalRecord && self.historyRecordNameMutableArray.count > 0 && [self.sectionFirstLetterMutableArrary[indexPath.section] isEqualToString:_config.historicalRecordTitle]) {//最近访问
                height = [self.config calculateCellHeightWithCount:self.historyRecordNameMutableArray.count];
            }
            
            if (![indexStr containsString:_config.historicalRecordTitle] && ![indexStr containsString:_config.popularCitiesTitle]) {//最近访问
                NSArray * sectionArray = self.dataMutableArray[indexPath.section];
                 height = [self.config calculateCellHeightWithCount:sectionArray.count] - 30;
              }
         }
    }
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section  {
    CGFloat height = 30;
    if (self.sectionFirstLetterMutableArrary.count > section && [self.sectionFirstLetterMutableArrary[section] isEqualToString:kHeaderCitiesSectionIndex]) {
        height = 0;
    }
    return height;
}

#pragma mark -- Data

- (void)initData {
    self.popularCitiesNameMutableArray = [NSMutableArray new];
    self.otherCitiesMutableArray = [NSMutableArray new];
    self.historyRecordMutableArray = [NSMutableArray new];
    self.historyRecordNameMutableArray = [NSMutableArray new];
    self.headerCitiesNameMutableArray = [NSMutableArray new];
    self.dataOpreation = [[XMCSDataOpreation alloc] initWithConfiguration:_config];
    self.currentCityModel =  [self.dataOpreation currentCity];
    self.historyRecordMutableArray = [[self.dataOpreation historyRecordCities] mutableCopy];
    [self.historyRecordMutableArray enumerateObjectsUsingBlock:^(XMCSBaseInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.historyRecordNameMutableArray addObject:obj.alias ? : obj.name];
    }];
    [self.config.popularCitiesMutableArray enumerateObjectsUsingBlock:^(XMCSPopularCitiesModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.popularCitiesNameMutableArray addObject:obj.name];
    }];
    XMWeakSelf(self);
    [self.dataOpreation arrayOfCityAndArea:^(NSMutableArray * _Nonnull data) {
        XMStrongSelf(self);
        [self configData:data];
    }];
    [self.headerView updateCurrentCity:self.currentCityModel.alias ? : self.currentCityModel.name];
}

- (void)configData:(NSMutableArray *)dataArr {
    self.dataMutableArray = [NSMutableArray arrayWithArray:[dataArr mutableCopy]];
    self.otherCitiesMutableArray = [dataArr mutableCopy];
    
//    [self.otherCitiesMutableArray enumerateObjectsUsingBlock:^(XMCSBaseInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        XMCSBaseInfoModel  * objs = [[XMCSBaseInfoModel alloc]init];
////        objs.name = obj.name;
////        objs.index = [NSString stringWithFormat:@"%ld",idx];
////        [self.otherCitiesMutableArray addObject:objs];
//    }];
    
    
    self.firstLetterMutableArrary = [self.dataOpreation.firstLetterArraryOfCityOrArea mutableCopy];
    self.sectionFirstLetterMutableArrary = [self.dataOpreation.firstLetterArraryOfCityOrArea mutableCopy];
    if (!self.config.hidePopularCities && self.config.popularCitiesMutableArray.count > 0) {
        [self insertPopularCitiesCellData];
    }
    if (!self.config.hideHistoricalRecord && [self.dataOpreation historyRecordCities].count > 0) {
        [self insertHistoricalRecordCellData];
    }
    [self.tableView reloadData];
}

- (void)insertPopularCitiesCellData {
    [self.dataMutableArray insertObject:@[@"****** 我是热门城市 Cell ******"] atIndex:0];
    [self.firstLetterMutableArrary insertObject:_config.popularCitiesAbbreviation atIndex:0];
    [self.sectionFirstLetterMutableArrary insertObject:_config.popularCitiesTitle atIndex:0];
}

- (void)insertHistoricalRecordCellData {
    [self.dataMutableArray insertObject:@[@"****** 我是最近访问 Cell ******"] atIndex:0];
    [self.firstLetterMutableArrary insertObject:_config.historicalRecordAbbreviation atIndex:0];
    [self.sectionFirstLetterMutableArrary insertObject:_config.historicalRecordTitle atIndex:0];
}

//- (void)insertHeaderCitiesCellData {
//    [self.dataMutableArray insertObject:@[@"****** 我是切换区县 Cell ******"] atIndex:0];
//    [self.firstLetterMutableArrary insertObject:@"区县" atIndex:0];
//    [self.sectionFirstLetterMutableArrary insertObject:kHeaderCitiesSectionIndex atIndex:0];
//}

#pragma mark -- Lazy

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
        _tableView.sectionIndexColor = _config.sectionIndexColor;
//        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        [_tableView registerClass:[XMCSTopToolsTableViewCell class] forCellReuseIdentifier:@"XMCSTopToolsTableViewCell"];
//        [_tableView registerClass:[XMCSTopToolsTableViewCell class] forCellReuseIdentifier:@"XMCSTopToolsTableViewCell1"];
        [_tableView registerClass:[XMCSContentTableViewCell class] forCellReuseIdentifier:@"XMCSContentTableViewCell"];

        _tableView.tableHeaderView = self.headerView;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UIButton *)searchButton {
    if (!_searchButton) {
        _searchButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 240, 30)];
        [_searchButton setTitle:_config.searchButtonTitle forState:UIControlStateNormal];
        [_searchButton.titleLabel setFont:[UIFont systemFontOfSize:12.0]];
        [_searchButton setTitleColor:_config.searchButtonTitleColor forState:UIControlStateNormal];
//        [_searchButton setImage:[XMCSFileManager getImageWithName:_config.searchButtonImageName] forState:UIControlStateNormal];
        [_searchButton setBackgroundColor:_config.searchButtonBackgroundColor];
        [_searchButton.layer setCornerRadius:30 / 2];
        [_searchButton addTarget:self action:@selector(searchButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchButton;
}

- (XMCSTableViewHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[XMCSTableViewHeaderView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40) hideSwitchButton:self.config.hideAreaSwitchButton];
        XMWeakSelf(self);
        [_headerView headerViewBlock:^(BOOL selected) {
            XMStrongSelf(self);
            if (selected) {
//                [self showOtherCityCell];
            }else {
//                [self hiddenOtherCityCell];
            }
        }];
    }
    return _headerView;
}

#pragma mark - Action

- (void)selectCityCallBack:(XMCSBaseInfoModel *)model {
    self.currentCityModel = model;
    [self.dataOpreation cacheCurrentCity:model];
    [self.headerView updateCurrentCity:model.alias ? : model.name];
    if (!_config.hideHistoricalRecord) {
        [self.dataOpreation insertHistoryRecordCityModel:model];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(viewController:didSelectCity:)]) {
        [self.delegate viewController:self didSelectCity:model];
    }
    [self leftBarButtonItemAction];
}

- (void)leftBarButtonItemAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchButtonAction:(UIButton *)sender {
//    XMCSSearchTableViewController *searchVC = [[XMCSSearchTableViewController alloc] initWithConfig:_config dataOpreation:_dataOpreation];
//    [searchVC selectCityBlock:^(XMCSBaseInfoModel * _Nonnull model) {
//        [self selectCityCallBack:model];
//    }];
//    UINavigationController *nvi = [[UINavigationController alloc] initWithRootViewController:searchVC];
//    [self presentViewController:nvi animated:NO completion:nil];
}

- (void)didSelectPopularCities:(XMCSPopularCitiesModel *)popularCitiesModel {
    NSArray *arr = [NSArray new];
    
    switch (popularCitiesModel.type) {
        case XMCSPopularCitiesTypeProvince: {
//            arr = [self.dataOpreation searchProvinceWithString:popularCitiesModel.name];
        }
            break;
        case XMCSPopularCitiesTypeCity: {
//            arr = [self.dataOpreation searchCityWithString:popularCitiesModel.name];
        }
            break;
        case XMCSPopularCitiesTypeArea: {
//            arr = [self.dataOpreation searchAreaWithString:popularCitiesModel.name];
        }
            break;
        default:
            break;
    }
    
    if (arr.count > 0) {
        [self selectCityCallBack:(XMCSBaseInfoModel *)arr[0]];
    }
}

#pragma maek -- 切换区县

//- (void)showOtherCityCell {
//    XMWeakSelf(self);
//    [self.dataOpreation otherCitiesWithCityModel:self.currentCityModel
//                                     resultArray:^(NSArray<XMCSBaseInfoModel *> * _Nonnull dataArray) {
//                                         XMStrongSelf(self);
//                                         if (dataArray.count > 0) {
////                                             [self insertHeaderCitiesCellData];
//                                             self.headerCitiesMutableArray = [dataArray mutableCopy];
//                                             [self.headerCitiesNameMutableArray removeAllObjects];
//                                             [dataArray enumerateObjectsUsingBlock:^(XMCSBaseInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                                                 [self.headerCitiesNameMutableArray addObject:obj.name];
//                                             }];
//                                             
//                                             [self.tableView beginUpdates];
//                                             [self.tableView insertSections:[[NSIndexSet alloc] initWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
//                                             [self.tableView endUpdates];
//                                         }
//                                     }];
//}

- (void)hiddenOtherCityCell {
    if (self.headerCitiesMutableArray.count > 0) {
        [self.headerCitiesNameMutableArray removeAllObjects];
        [self.headerCitiesMutableArray removeAllObjects];
        [self.dataMutableArray removeObjectAtIndex:0];
        [self.sectionFirstLetterMutableArrary removeObjectAtIndex:0];
        [self.firstLetterMutableArrary removeObjectAtIndex:0];
        [self.tableView beginUpdates];
        [self.tableView deleteSections:[[NSIndexSet alloc] initWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
    }
}

@end
